﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using NHibernate.Type;
using NHibernate.SqlTypes;
using YasharEl.Infrastructure.Core.Personification;
using YasharEl.Infrastructure.EntityModel;
using NHibernate.Dialect;

namespace YasharEl.Infrastructure.Core.PersistenceModel.NHibernate.Personification.UserTypes
{
    public class GenderEnumerationType : PrimitiveType
    {
        public GenderEnumerationType()
            : base(new SqlType(DbType.String))
        {
        }

        public override object Get(IDataReader rs, int index)
        {
            object o = rs[index];
            var value = Convert.ToString(o);
            try
            {
                return Gender.FromShortName<Gender>(value);
            }
            catch (InvalidEnumerationException e)
            {
                throw new GenderEnumerationException(value, e.ToString());
            }
        }

        public override object Get(IDataReader rs, string name)
        {
            int ordinal = rs.GetOrdinal(name);
            return Get(rs, ordinal);
        }

        public override Type ReturnedClass
        {
            get { return typeof(Gender); }
        }

        public override object FromStringValue(string xml)
        {
            if (string.IsNullOrEmpty(xml))
                return null;
            string lowerGender = xml.ToLower();
            if (lowerGender == "f")
                return Gender.Female;
            else if (lowerGender == "m")
                return Gender.Male;
            return null;
        }

        public override string Name
        {
            get { return "Gender"; }
        }

        public override void Set(IDbCommand cmd, object value, int index)
        {
            var parameter = (IDataParameter)cmd.Parameters[index];

            var val = (Enumeration)value;

            parameter.Value = val.Value;
        }

        public override string ObjectToSQLString(object value, Dialect dialect)
        {
            if (value == null)
                return null;
            Gender gender = value as Gender;
            if (gender == null)
                return null;

            return gender.ShortName;
        }

        public override Type PrimitiveClass
        {
            get { return typeof(Gender); }
        }

        public override object DefaultValue
        {
            get { return null; }
        }
    }
}
